package tom.client.admin;

import java.util.ArrayList;
import java.util.List;

import tom.shared.Program;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.TreeViewModel;

public class FormTreeViewModel implements TreeViewModel {

	private static class FormCell extends AbstractCell<Program> {
		@Override
		public void render(Context context, Program value, SafeHtmlBuilder sb) {
			if (value != null) {
				sb.appendEscaped(value.pgmName);
			}
		}
	}

	public void clearData() {
		moduleList.clear();
		formList.clear();
	}

	public List<Program> filter(List<Program> allForm, String module) {
		List<Program> list = new ArrayList<Program>();
		for (Program form : allForm)
			if (module.equals(form.module))
				list.add(form);
		return list;
	}

	private List<String> moduleList;

	private List<Program> formList;

	public FormTreeViewModel(List<Program> formList) {
		this.formList = formList;
		moduleList = new ArrayList<String>();
		for (Program f : formList) {
			if (moduleList.indexOf(f.module) < 0)
				moduleList.add(f.module);
		}
	}

	@Override
	public <T> NodeInfo<?> getNodeInfo(T value) {
		if (value == null) {
			return new DefaultNodeInfo<String>(new ListDataProvider<String>(
					moduleList), new TextCell());
		} else if (value instanceof String) {
			return new DefaultNodeInfo<Program>(new ListDataProvider<Program>(filter(
					formList, (String) value)), new FormCell());
		} else
			return null;
	}

	@Override
	public boolean isLeaf(Object value) {
		return value instanceof Program;
	}

}
